from django.contrib.auth.models import AbstractUser
from django.db import models


# 基类
class BaseModel(models.Model):
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    update_time = models.DateTimeField('更新时间', auto_now=True)


# 部门类
class Department(BaseModel):
    name = models.CharField("部门", max_length=50)
    def __str__(self):
        return self.name

    class Meta:
        db_table = "department"


# 职责类
class Duty(BaseModel):
    name = models.CharField("工作职责", max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'duty'


# 员工模型类
class Staff(models.Model):
    SEX_CHOICE = (
        (1, '男'),
        (0, '女')
    )
    name = models.CharField('姓名', max_length=20)
    sex = models.SmallIntegerField('性别', default=1, choices=SEX_CHOICE)
    phone = models.CharField('手机号', max_length=11)
    email = models.EmailField('邮箱', max_length=50)
    department = models.ForeignKey(Department, on_delete=models.CASCADE, verbose_name='部门')
    duty = models.ForeignKey(Duty, on_delete=models.CASCADE, verbose_name="工作职责")

    def __str__(self):
        return self.name

    class Meta:
        db_table = "staff"


# 权限类型(角色)
class PermissionType(models.Model):
    name = models.CharField('权限类型名称', max_length=30)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "permission_type"
        verbose_name_plural = '权限类型(角色)'


# 用户类  多对多关系 django会自动维护第三张表
class User(AbstractUser):
    phone = models.CharField('手机号', max_length=11, null=True, unique=True, blank=True)
    last_login = models.DateTimeField('上次登录',  null=True, blank=True)
    role = models.ManyToManyField(PermissionType, )

    def __str__(self):
        return self.username

    class Meta:
        db_table = "user_tb"
        verbose_name_plural = '用户表'


# 权限表
# name  varchar(30)  '权限名称'
# code_name  varchar(300)  '权限识别名称'
# type_name fk  --->PermissionType
class Permission(models.Model):
    name = models.CharField('权限名称', max_length=30)
    code_name = models.CharField('权限识别名称', max_length=300)
    type_name = models.ForeignKey(PermissionType, on_delete=models.CASCADE, verbose_name='角色')

    def __str__(self):
        return self.name

    class Meta:
        db_table = "permission"
        verbose_name_plural = '权限表'


# 用户组
class UserGroup(models.Model):
    """用户组的模型类"""
    name = models.CharField('组名称',max_length=30)
    user = models.ManyToManyField(User)
    # 更改模型类: 改为多对多
    permission = models.ManyToManyField(Permission)

    class Meta:
        db_table = 'user_group'
        verbose_name_plural = '用户组'

    def __str__(self):
        return self.name

















